<template>
  <div class="page-modal">
    <el-dialog v-model="dialogVisible" :title="title" :width="width" center destroy-on-close>
      <config-form v-bind="modalConfig" v-model="formData" ref="formRef">
        <!-- 表单内部扩展内容 -->
        <template v-for="item in modalConfig.formItems" :key="item.field" #[item.slotName]>
          <slot :name="item.slotName" v-if="item.slotName" />
        </template>
      </config-form>
      <!-- 外部扩展内容 -->
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" v-loading="btnLoading" @click="handleConfirmClick">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, defineExpose } from 'vue'
import ConfigForm from '@/base-ui/form/index.vue'

const props = defineProps({
  // 模态框配置
  modalConfig: {
    type: Object,
    required: true
  },
  // 模态框标题
  title: {
    type: String,
    default: ''
  },
  // 默认信息
  defaultInfo: {
    type: Object,
    default: () => ({})
  },
  //   模态框宽度
  width: {
    type: String,
    default: '30%'
  },
  // loading状态
  btnLoading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['submitData'])

// 模态框显示
const dialogVisible = ref(false)
const formOriginData: any = {}

const formItems = props.modalConfig?.formItems ?? []
// 动态生成表单初始值
for (const item of formItems) {
  if (item.type === 'switch' || item.type === 'radio') {
    formOriginData[item.field] = false
  } else if (item.type === 'checkbox' || item.type === 'upload') {
    formOriginData[item.field] = []
  } else {
    formOriginData[item.field] = ''
  }
}
const formData = ref(formOriginData)

// 打开模态框
const openModal = () => {
  dialogVisible.value = true
}

// 关闭模态框
const closeModal = () => {
  dialogVisible.value = false
  formData.value = formOriginData
}

watch(
  () => props.defaultInfo,
  (newValue) => {
    for (const item of props.modalConfig!.formItems) {
      formData.value[`${item.field}`] = newValue[`${item.field}`]
    }
  }
)
// 表单引用
const formRef = ref<InstanceType<typeof ConfigForm>>()

//点击确定
const handleConfirmClick = () => {
  formRef.value?.ruleFormRef?.validate((valid: boolean) => {
    if (valid) {
      emit('submitData', formData)
    }
  })
}

defineExpose({
  openModal,
  closeModal
})
</script>
